package com.itheima.admin.contorller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.exception.MyException;
import com.itheima.common.result.JsonResult;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Flavor;
import com.itheima.entity.dto.DishDTO;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.FlavorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhengbinghua
 * @since 2023-03-02
 */
@RestController
@RequestMapping("/dish")
@Api(tags = "菜品分类")
public class DishController {
@Autowired
    private DishService dishService;
@Autowired
  private FlavorService flavorService;
@Autowired
private CategoryService categoryService;
@Autowired
private CacheManager cacheManager;
/**
 * 添加菜品
 */
    @PostMapping
    @ApiOperation(value = "添加菜品")
    @CachePut(value = "addDish",key = "#dishDTO.id")
public JsonResult addDish(@RequestBody DishDTO dishDTO){
        //添加菜品
        Dish dish = new Dish();
        BeanUtil.copyProperties(dishDTO, dish);
        dishService.save(dish);
        //添加菜品对应口味
        List<Flavor> flavorList = dishDTO.getFlavorList();
        //口味表的dishid和菜品表一致时，添加口味
        /**循环方式插入口味
         * */
        //这个集合用来存放dishid
        List<Flavor> flavors = new ArrayList<>();
        for (Flavor flavor : flavorList) {
            flavor.setDishId(dishDTO.getId());
            flavors.add(flavor);
        }
        /**stream流
         * */
        //List<Flavor> flavors = flavorList.stream()
        //        .peek(flavor -> flavor.setDishId(dishDTO.getId())).collect(Collectors.toList());
        flavorService.saveBatch(flavors);
        //返回前端
       return JsonResult.success("添加成功！");
    }
    /**
     * 修改菜品
     *
     * @return
     */
    @PutMapping
    @ApiOperation(value = "修改菜品")
    @CacheEvict(value = "updateDish",key ="#dishDTO.id" )
    public JsonResult updateDish(@RequestBody DishDTO dishDTO){
        //判断菜品是否存在
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
         wrapper.eq(Dish::getName, dishDTO.getName());
        Dish dish = dishService.getOne(wrapper);
        if (null==dish){
            throw new MyException(404, "菜品不存在，修改失败");
        }
        //封装dish对象
        Dish dish1 = new Dish();
        BeanUtil.copyProperties(dishDTO, dish);
        //修改菜品
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Dish::getId,dishDTO.getId());
        dishService.update(dish1,updateWrapper);
        //删除旧的口味信息
        LambdaQueryWrapper<Flavor> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Flavor::getDishId,dishDTO.getId());
        flavorService.remove(wrapper1);
       //添加新口味
        List<Flavor> flavorList = dishDTO.getFlavorList();
        //新建一个空集合用来存放dishid
        ArrayList<Flavor> list = new ArrayList<>();
        for (Flavor flavor : flavorList) {
            flavor.setDishId(dishDTO.getId());
            list.add(flavor);
        }
        flavorService.saveBatch(list);
        //返回前端
        return JsonResult.success("添加成功！");
           }
           /**
            * 删除菜品
            *
            * @return
            */
           @DeleteMapping
           @ApiOperation(value = "删除菜品")
           @CacheEvict(value = "deleteDish",key = "#ids")
           public JsonResult deleteDish(String ids){
               //按，分割字符串，获取对应id
               String[] split = ids.split(",");
               //删除dish信息
              dishService.removeBatchByIds(Arrays.asList(split));
              //删除flavor表口味信息
               LambdaQueryWrapper<Flavor> wrapper = new LambdaQueryWrapper<>();
               wrapper.in(Flavor::getDishId,ids);
               flavorService.remove(wrapper);
              return JsonResult.success("删除菜品成功！");
           }
/**
 * 根据id查询菜品信息
 *
 * @return
 */
@GetMapping("{id}")
@ApiOperation(value = "查询菜品信息")
@Cacheable (value = "getDishByid",key = "#id")
public JsonResult getDishByid(@PathVariable String id){
    //获取菜品信息
     Dish dish = dishService.getById(id);
    //获取口味信息
    LambdaQueryWrapper<Flavor> wrapper1 = new LambdaQueryWrapper<>();
    wrapper1.eq(Flavor::getDishId,id);
    List<Flavor> flavors = flavorService.list(wrapper1);
    //封装前端对象
    DishDTO dishDTO = new DishDTO();
    //把dish信息转移给dto
    BeanUtil.copyProperties(dish, dishDTO);
    //设置口味
    dishDTO.setFlavorList(flavors);
    return JsonResult.success(dishDTO);
}
/***菜品分页查询
 *
 * @return*/
@GetMapping("page")
@ApiOperation(value = "菜品分页查询")
@Cacheable(value=" getDishinfoByPage",key = "#page +'_'+pageSize")
public JsonResult getDishinfoByPage(@ApiParam("名字") String name,
                                    @ApiParam("类型") String type,
                                    @ApiParam("页码") Integer page,
                                    @ApiParam("每页显示条数") Integer pageSize) {
  //封装页面信息
    Page<Dish> pageInfo = new Page<>(page, pageSize);
    //新建对象
    Page<DishDTO> dishDtoPage = new Page<>();
    //封装条件
    LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
    wrapper.like(Dish::getName, name);
    wrapper.eq(Dish::getType, type);
    //分页查询
    dishService.page(pageInfo, wrapper);

    //拷贝属性，无视分页记录，分页记录另外处理
    BeanUtil.copyProperties(pageInfo, dishDtoPage, "records");
    //获得dish表的分页记录
    List<Dish> records = pageInfo.getRecords();
    //处理records集合，并且添加菜品名字，用于前端分页展示
    List<DishDTO> list = records.stream().map(dish -> {
        //新建dishdto对象
        DishDTO dishDTO = new DishDTO();
        //属性拷贝,这里dto少了菜品名这个属性
        BeanUtil.copyProperties(dish, dishDTO);
        //获得菜品id
        String categoryId = dish.getCategoryId();
        //通过id获得菜品名字
        Category category = categoryService.getById(categoryId);
        if (null != category) {
            //获得菜品名
            String categoryName = category.getName();
            //dto设置属性
            dishDTO.setCategoryName(categoryName);
        }
        //返回dto对象
        return dishDTO;
    }).collect(Collectors.toList());
    //给pagedto对象设置records属性值
    dishDtoPage.setRecords(list);
    //返回前端
    return JsonResult.success(dishDtoPage);
}
/**
 * 菜品下拉列表
 *
 * @return
 **/
@ApiOperation(value = "菜品下拉列表")
@GetMapping("list")
@Cacheable(value = "getDishList",key = "#categoryId")
    public JsonResult getDishList(String categoryId){
    LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
     wrapper.eq(Dish::getCategoryId, categoryId);
     //按菜品sort排序
    wrapper.orderByDesc(Dish::getSort);
    //按更新时间排序
    wrapper.orderByDesc(Dish::getUpdateTime);
    //菜品必须是在售状态
    wrapper.eq(Dish::getStatus,"1");
    //获取菜品列表
    List<Dish> dishList = dishService.list(wrapper);
    return JsonResult.success(dishList);
}
/***菜品起售/停售
 *
 * @return*/
@ApiOperation(value="菜品起售/停售")
@PostMapping("status/{status}")
    public JsonResult changeDishStaus(@PathVariable Integer status, String ids){
    JsonResult result = dishService.changeDishStatus(status, ids);
    return result;
}
}
